package cn.johnyu.demo;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(filterName = "authenFilter", urlPatterns = "/api/*")
public class AuthenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object user = request.getSession().getAttribute("user");
        if(user!=null){
            filterChain.doFilter(servletRequest, servletResponse);
        }
        else{
            request.getSession().setAttribute("msg","请先登录");
//            使用请求转发,可以达到index.jsp,但会导致地址栏保持原样，进而导致css等资源无法加载及其它一系列的问题
//            request.getRequestDispatcher("/index.jsp").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }

    }

    public void destroy() {
        System.out.println("MyFilter destroy..........");
    }
}
